package com.qianfeng.smartplatform.log;

//
//                            _ooOoo_  
//                           o8888888o  
//                           88" . "88  
//                           (| -_- |)  
//                            O\ = /O  
//                        ____/`---'\____  
//                      .   ' \\| |// `.  
//                       / \\||| : |||// \  
//                     / _||||| -:- |||||- \  
//                       | | \\\ - /// | |  
//                     | \_| ''\---/'' | |  
//                      \ .-\__ `-` ___/-. /  
//                   ___`. .' /--.--\ `. . __  
//                ."" '< `.___\_<|>_/___.' >'"".  
//               | | : `- \`.;`\ _ /`;.`/ - ` : | |  
//                 \ \ `-. \_ __\ /__ _/ .-` / /  
//         ======`-.____`-.___\_____/___.-`____.-'======  
//                            `=---='  
//  
//         .............................................  
//                  佛祖镇楼                  BUG辟易  
//          佛曰:  
//                  写字楼里写字间，写字间里程序员；  
//                  程序人员写程序，又拿程序换酒钱。  
//                  酒醒只在网上坐，酒醉还来网下眠；  
//                  酒醉酒醒日复日，网上网下年复年。  
//                  但愿老死电脑间，不愿鞠躬老板前；  
//                  奔驰宝马贵者趣，公交自行程序员。  
//                  别人笑我忒疯癫，我笑自己命太贱；  
//  


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qianfeng.smartplatform.exceptions.MyBaseErrorxception;
import com.qianfeng.smartplatform.log.annotations.LogAnnotation;
import com.qianfeng.smartplatform.pojo.Operlog;
import com.qianfeng.smartplatform.security.BaseUser;
import com.qianfeng.smartplatform.service.OperLogService;
import com.qianfeng.smartplatform.utils.RequestUtil;
import com.qianfeng.smartplatform.utils.SecurityUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.*;

/**
 * Created by Jackiechan on 2021/12/23/0:43
 *
 * @author Jackiechan
 * @version 1.0
 * @since 1.0
 */
@Aspect
@Component
public class LogAdvice {

    private OperLogService operLogService;

    private ThreadPoolExecutor complateFutureExecutor;

    @Autowired
    public void setComplateFutureExecutor(ThreadPoolExecutor complateFutureExecutor) {
        this.complateFutureExecutor = complateFutureExecutor;
    }

    @Autowired
    public void setOperLogService(OperLogService operLogService) {
        this.operLogService = operLogService;
    }

    private ObjectMapper objectMapper;

    @Autowired
    public void setObjectMapper(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Pointcut("@annotation(com.qianfeng.smartplatform.log.annotations.LogAnnotation)")
    public void pointcut() {

    }

    @AfterReturning(value = "pointcut()", returning = "result")
    public void after(JoinPoint joinPoint, Object result) {
        //将不一样的数据生成好
        Operlog operlog = new Operlog();
        operlog.setStatus(1);
        operlog.setErrorMsg("200 OK");
        try {
            operlog.setJsonResult(objectMapper.writeValueAsString(result));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        //将其他数据自动生成并保存到数据库
        addLog(joinPoint, operlog);
    }


    @AfterThrowing(value = "pointcut()", throwing = "e")
    public void afterThrow(JoinPoint joinPoint, Throwable e) {
        //将不一样的数据生成好
        Operlog operlog = new Operlog();
        operlog.setStatus(0);
        if (e instanceof MyBaseErrorxception) {
            operlog.setErrorMsg(((MyBaseErrorxception) e).getCode() + e.getMessage());
        } else {
            operlog.setErrorMsg(e.getMessage());
        }
        //将其他数据自动生成并保存到数据库
        addLog(joinPoint, operlog);
    }

    //生成日志对象
    private void addLog(JoinPoint joinPoint, Operlog operlog) {
        //在外面获取避免线程的原因释放了request或者子线程无法获数据
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        BaseUser user = SecurityUtils.getUser();
        CompletableFuture.runAsync(() -> {
            //获取请求
            Map<String, String> osAndBrowserInfo = RequestUtil.getOsAndBrowserInfo(request);//客户端信息
            //获取当前登录用户

            //获取目标类
            // Class<?> targetClass = joinPoint.getTarget().getClass();
            //获取目标方法
            String methodName = joinPoint.getSignature().getName();
            MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
            Method method = methodSignature.getMethod();
            //获取参数
            Object[] arguments = joinPoint.getArgs();
            LogAnnotation logAnnotation = method.getAnnotation(LogAnnotation.class);
            if (logAnnotation != null) {
                operlog.setBusinessType(logAnnotation.business_type());
                operlog.setTitle(logAnnotation.title());
                operlog.setOperatorType(1);
//            try {
//                int mobile = request.getIntHeader("mobile");
//                if (mobile == 2) {
//                    operlog.setOperatorType(mobile);
//                }
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
                String os = osAndBrowserInfo.get("os");

                switch (os) {
                    case "Android":
                    case "IPhone":
                        operlog.setOperatorType(2);//来自于移动端
                        break;
                    case "Windows":
                    case "Mac":
                    case "Unix":
                        operlog.setOperatorType(1);//来自于PC
                        break;
                    default:
                        operlog.setOperatorType(0);//来自于其他
                        break;
                }


                operlog.setMethod(methodName);
                operlog.setRequestMethod(request.getMethod());

                operlog.setOperTime(new Date());
                String ip = RequestUtil.getRemoteHost(request);
                operlog.setOperIp(ip);
                operlog.setOperUrl(request.getRequestURI());
                operlog.setOperLocation(RequestUtil.getLocationByIp(ip));
//            operlog.setOperLocation("先随便写一个");
                try {
                    operlog.setOperParam(objectMapper.writeValueAsString(arguments));
                    operlog.setOperName(user.getUsername());//设置访问者
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
            operLogService.addOperLog(operlog);
        },complateFutureExecutor);
    }
}
